#include "../source/server.hpp"

//这些是LoopThread模块的内容

//管理所有的连接
std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;
EventLoop base_loop;
std::vector<LoopThread> threads(2);
int next_loop = 0;

void ConnectionDestroy(const PtrConnection& conn)
{
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection& conn)
{
    DBG_LOG("NEW CONNECTION:%p", conn.get());
}
void OnMessage(const PtrConnection& conn, Buffer* buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World";
    conn->Send(str.c_str(), str.size());
}

void NewConnection(int fd)
{
    conn_id++;
    next_loop = (next_loop + 1) % 2;
    PtrConnection conn(new Connection(threads[next_loop].GetLoop(), conn_id, fd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    // conn->SetMessageCallback(OnMessage);
    conn->SetSvrClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRealse(10); //启动非活跃超时销毁
    conn->Establised(); //就绪初始化
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("NEW------------------------");
}

int main()
{
    srand(time(NULL));
    Acceptor acceptor(&base_loop, 8085);
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));
    acceptor.Listen();  //将自己挂入监听
    while (1)
    {
        base_loop.Start();
    }
    return 0;
}